<template>
  <div class="login-container">
    <div class="login-box">
      <h2>系统登录</h2>
      <div class="input-group">
        <div class="input-item">
          <i class="input-icon">👤</i>
          <input
            type="text"
            v-model="username"
            placeholder="请输入用户名"
            @keyup.enter="handleLogin"
          />
        </div>
        <div class="input-item">
          <i class="input-icon">🔒</i>
          <input
            type="password"
            v-model="password"
            placeholder="请输入密码"
            @keyup.enter="handleLogin"
          />
        </div>
      </div>
      <button @click="handleLogin" :disabled="loading">
        {{ loading ? '登录中...' : '登录' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { useUserStore } from '@/store/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const username = ref('')
const password = ref('')
const loading = ref(false)

// 检查URL中是否有登录数据
onMounted(() => {
  const loginData = route.query.loginData
  if (loginData) {
    try {
      console.log('检测到登录数据:', loginData)
      const data = JSON.parse(decodeURIComponent(loginData))
      console.log('解析后的登录数据:', data)
      
      // 询问用户是否要使用管理后台的登录信息
      if (confirm('检测到管理后台的登录信息，是否使用该信息登录？')) {
        // 使用管理后台的登录信息
        userStore.setToken(data.token)
        userStore.setUserInfo({
          userName: data.userName,
          userType: data.userType,
          id: data.id,
          avatar: data.avatar || '' // 如果没有头像则使用空字符串
        })
        console.log('已更新用户信息:', userStore.userInfo)
        
        // 跳转到首页
        router.push('/')
      } else {
        // 用户选择不使用管理后台的登录信息，清除URL中的参数
        router.replace({ query: {} })
      }
    } catch (error) {
      console.error('解析登录数据失败:', error)
      alert('登录数据解析失败，请重新登录')
    }
  }
})

const handleLogin = async () => {
  if (!username.value || !password.value) {
    alert('请输入用户名和密码')
    return
  }

  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('username', username.value)
    params.append('password', password.value)

    const response = await axios.post('/app/auth/login', params)
    console.log('登录响应:', response.data)

    if (response.data.code === 200) {
      const { token, userName, avatar, userType, id } = response.data.data
      // 使用Pinia存储用户信息
      userStore.setToken(token)
      userStore.setUserInfo({
        userName,
        avatar: avatar || '',
        userType,
        id
      })
      console.log('已更新用户信息:', userStore.userInfo)

      // 获取重定向地址
      const redirect = route.query.redirect || '/'
      // 跳转到重定向地址或首页
      router.push(redirect)
    } else {
      alert(response.data.message || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    alert(error.response?.data?.message || '登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  /* background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%); */
  overflow: hidden;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #1890ff;
  font-size: 28px;
  font-weight: 600;
}

.input-group {
  margin-bottom: 24px;
}

.input-item {
  position: relative;
  margin-bottom: 20px;
}

.input-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 18px;
  color: #999;
}

input {
  width: 100%;
  padding: 12px 12px 12px 40px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s;
  background: white;
}

input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

input::placeholder {
  color: #999;
}

button {
  width: 100%;
  padding: 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

button:hover:not(:disabled) {
  background-color: #40a9ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

button:disabled {
  background-color: #bae7ff;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-box {
    width: 90%;
    padding: 30px 20px;
  }
}
</style>
